<template>
  <view class="comment_box l_f_c">
    <!--  <view class="c_total">评论 {{ props.tableTotal }}</view>-->
    <template v-if="dataList && dataList.length">
      <view v-for="(item1, index1) in dataList" :key="item1.id" class="c_comment nvueW">
        <!-- 一级评论 -->
        <CommonComp
            :data="item1"
            :myInfo="myInfo"
            @deleteClick="() => deleteClick({ item1, index1 })"
            @likeClick="() => likeClick({ item1, index1 })"
            @replyClick="() => replyClick({ item1, index1 })"
        />
        <view v-if="item1.comment_count>0" class="children_item">
          <!-- 二级评论 -->
          <CommonComp
              v-for="(item2, index2) in item1.children"
              :key="item2.id"
              :data="item2"
              :isTwo="true"
              :myInfo="myInfo"
              :pData="item1"
              @deleteClick="() => deleteClick({ item1, index1, item2, index2 })"
              @likeClick="() => likeClick({ item1, index1, item2, index2 })"
              @replyClick="() => replyClick({ item1, index1, item2, index2 })"
          />
          <!-- 折叠二级评论 -->
          <view
              v-if="!expandTxtShow({ item1, index1 })"
              class="shrink_reply l_f_r l_al_c"
              @tap="() => shrinkReplyFun({ item1, index1 })"
          >
            <text class="txt text_5_24"> ———收起回复内容</text>
            <uni-icons color="#555555" size="16" type="up"></uni-icons>
          </view>
          <!-- 展开二级评论 -->
          <view
              v-if="expandTxtShow({ item1, index1 })"
              class="expand_reply l_f_r l_al_c"
              @tap="() => expandReplyFun({ item1, index1 })"
          >
            <text class="txt text_5_24"> ———展开{{
                item1.comment_count - (item1.children && item1.children.length || 0)
              }}条回复
            </text>
            <uni-icons color="#555555" size="16" type="down"></uni-icons>
          </view>

        </view>
      </view>
    </template>


    <!-- 空盒子 -->
    <view v-else class="empty_box nvueW l_f_c_c_c">
      <uni-icons color="#c0c0c0" size="36" type="chatboxes"></uni-icons>
      <view class="l_f_r_c_c">
        <text class="txt"> 这里是一片荒草地,</text>
        <text class="txt click" @click="() => newCommentFun()">说点什么...</text>
      </view>
    </view>
    <view v-if="dataList && dataList.length" class="l_f_r_c_c jzLoding">
      <view v-if="dataList.length<fTotal" class="jzText" @click="handleAddPage">加载更多</view>
    </view>
    <!-- 评论弹窗 -->
    <uni-popup ref="cPopupRef" :safe-area="false" type="bottom" @change="popChange">
      <view class="c_popup_box">
        <view class="reply_text l_f_r">
          <template v-if="Object.keys(replyTemp).length">
            <text class="text_aid">回复给</text>
            <image :src="(replyTemp.item2 ? replyTemp.item2.user_avatar : replyTemp.item1.user_avatar)||defaultAvatar"
                   class="user_avatar"/>
            <text class="text_main">{{ replyTemp.item2 ? replyTemp.item2.user_name : replyTemp.item1.user_name }}</text>
          </template>
          <text v-else class="text_main">发表新评论</text>
        </view>
        <view class="content11">
          <view class="text_area">
            <up-textarea
                v-model="commentValue"
                :placeholder="commentPlaceholder"
                autoHeight
                class="text_area"
                maxlength="300"
                trim
                type="textarea"
            ></up-textarea>
          </view>
          <view class="send_btn l_f_r_c_c" @tap="() => sendClick()">
            <text class="text_w text_5_24">发送</text>
          </view>
        </view>
      </view>
    </uni-popup>
    <!-- 删除弹窗 -->
    <uni-popup ref="delPopupRef" type="dialog">
      <uni-popup-dialog
          :before-close="true"
          content="确定删除这条评论吗?"
          mode="base"
          title=""
          @close="delCloseFun"
          @confirm="delConfirmFun"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup>
import CommonComp from "./componets/common";
import {reactive, ref, watch, computed,} from "vue";

const defaultAvatar = "https://pili-vod.guanxikeji.com/fubao/img/1755758365748.png"

const props = defineProps({
  /** 登陆用户信息
   *    id: number // 登陆用户id
   *    user_name: number // 登陆用户名
   *    user_avatar: string // 登陆用户头像地址
   */
  myInfo: {
    type: Object,
    default: () => {
    },
  },
  /** 文章作者信息
   *    id: number // 文章作者id
   *    user_name: number // 文章作者名
   *    user_avatar: string // 文章作者头像地址
   */
  userInfo: {
    type: Object,
    default: () => {
    },
  },
  /** 评论列表
   *    id: number // 评论id
   *    parent_id: number // 父级评论id
   *    reply_id: number // 被回复人评论id
   *    reply_name: string // 被回复人名称
   *    user_name: string // 用户名
   *    user_avatar: string // 评论者头像地址
   *    user_content: string // 评论内容
   *    is_like: boolean // 是否点赞
   *    like_count: number // 点赞数统计
   *    create_time: string // 创建时间
   */
  tableData: {
    type: Array,
    default: () => [],
  },
  // 评论总数
  tableTotal: {
    type: Number,
    default: 0,
  },
  // 评论删除模式
  // bind - 当被删除的一级评论存在回复评论, 那么该评论内容变更显示为[当前评论内容已被移除]
  // only - 仅删除当前评论(后端删除相关联的回复评论, 否则总数显示不对)
  // all - 删除所有评论包括回复评论
  deleteMode: {
    type: String,
    default: "all",
  },
  fTotal: {
    type: Number,
    default: 0,
  }
});
const emit = defineEmits([
  "update:tableTotal",
  "likeFun", // 点赞事件
  "replyFun", // 回复事件
  "deleteFun", // 删除事件
  "getMoreReply",// 获取更多回复
  "handleAddPage",
]);

// 渲染数据(前端的格式)
let dataList = ref([]);
watch(
    () => props.tableData,
    (newVal) => {
      if (newVal && newVal.length !== dataList.value.length) {
        // let temp = props.tableData;
        // dataList.value = treeTransForm(temp);
        dataList.value = newVal
      }
    },
    {deep: true, immediate: true}
);

// 数据转换
function treeTransForm(data) {
  let newData = JSON.parse(JSON.stringify(data));
  let result = [];
  let map = {};
  newData.forEach((item, i) => {
    item.author = item.user_id === props.userInfo.user_id; // 是否为作者 显示标记
    map[item.id] = item;
  });
  newData.forEach((item) => {
    let parent = map[item.granddad_id];
    if (parent) {
      (parent.children || (parent.children = [])).push(item); // 所有回复
      if (parent.children.length === 1) {
        (parent.childrenShow = []).push(item); // 显示的回复
      }
    } else {
      result.push(item);
    }
  });
  return result;
}

// 点赞
let setLike = (item) => {
  item.is_like = !item.is_like;
  item.like_count = item.is_like ? item.like_count + 1 : item.like_count - 1;
};

function likeClick({item1, index1, item2, index2}) {
  let item = item2 || item1;
  setLike(item);
  emit("likeFun", {params: item}, (res) => {
    // 请求后端失败, 重置点赞
    setLike(item);
  });
}

// 回复
let cPopupRef = ref(null); // 弹窗实例
let replyTemp = reactive({}); // 临时数据
function replyClick({item1, index1, item2, index2}) {
  replyTemp = JSON.parse(JSON.stringify({item1, index1, item2, index2}));
  console.log(item1, index1, item2, index2)
  cPopupRef.value.open();
}

// 发起新评论
let isNewComment = ref(false); // 是否为新评论
defineExpose({newCommentFun});

function newCommentFun() {
  isNewComment.value = true;
  cPopupRef.value.open();
}

// 评论弹窗
let focus = ref(false);

function popChange(e) {
  // 关闭弹窗
  if (!e.show) {
    commentValue.value = ""; // 清空输入框值
    replyTemp = {}; // 清空被回复人信息
    isNewComment.value = false; // 恢复是否为新评论默认值
  }
  focus.value = e.show;
}

let commentValue = ref(""); // 输入框值
let commentPlaceholder = ref("说点什么..."); // 输入框占位符

// 发送评论
function sendClick({item1, index1, item2, index2} = replyTemp) {
  let item = item2 || item1;
  let params = {};
  // 新评论
  if (isNewComment.value) {
    params = {
      id: null, // 评论id
      granddad_id: null, // 指向祖先的评论id
      parent_id: null, // 父级评论id
      reply_id: null, // 被回复评论id
      reply_name: null, // 被回复人名称
    };
  } else {
    // 回复评论
    params = {
      id: item.id, // 评论id
      granddad_id: item1.id,// 指向祖先的评论id
      parent_id: item?.parent_id ?? item.id, // 父级评论id
      reply_id: item.id, // 被回复评论id
      reply_name: item.user_name, // 被回复人名称
    };
  }
  params = {
    ...params,
    user_id: props.myInfo.user_id, // 用户id
    user_name: props.myInfo.user_name, // 用户名
    user_avatar: props.myInfo.user_avatar, //  用户头像地址
    user_content: commentValue.value, // 用户评论内容
    is_like: false, // 是否点赞
    like_count: 0, // 点赞数统计
    createTime: new Date().getTime(), // 创建时间
    owner: true, // 是否为所有者 所有者可以进行删除 管理员默认true
  };
  uni.showLoading({
    title: "正在发送",
    mask: true,
  });
  emit("replyFun", {params}, (res) => {
    uni.hideLoading();
    // 拿到后端返回的id赋值, 因为删除要用到id
    params = {...res.data,};
    console.log(res, '>>>', params, 999)

    // 新评论
    if (isNewComment.value) {
      dataList.value.push(params);
    } else {
      // 回复
      let c_data = dataList.value[index1];
      (c_data.children || (c_data.children = [])).push(params);
      c_data.comment_count += 1

      // 如果已展开所有回复, 那么此时插入children长度会大于childrenShow长度1, 所以就直接展开显示即可
      // if (c_data.children.length === (c_data.childrenShow || (c_data.childrenShow = [])).length + 1) {
      //   c_data.childrenShow.push(params);
      // }
    }
    emit("update:tableTotal", props.tableTotal + 1);
    cPopupRef.value.close();
  });
}

// 删除
const delPopupRef = ref(null);
let delTemp = reactive({}); // 临时数据
function deleteClick({item1, index1, item2, index2}) {
  delTemp = JSON.parse(JSON.stringify({item1, index1, item2, index2}));
  delPopupRef.value.open();
}

// 关闭删除弹窗
function delCloseFun() {
  delTemp = {};
  delPopupRef.value.close();
}

// 确定删除
function delConfirmFun({item1, index1, item2, index2} = delTemp) {
  console.log(item1, index1, item2, index2)
  let c_data = dataList.value[index1];
  uni.showLoading({
    title: "正在删除",
    mask: true,
  });
  // 删除二级评论
  if (index2 >= 0) {
    emit("deleteFun", {id: item2.id}, (res) => {
      if (res.errno == 0) {
        emit("update:tableTotal", props.tableTotal - res.data || 0);
        c_data.children.splice(index2, 1);
      }
      uni.hideLoading();

    });
  } else {
    emit("deleteFun", {id: item1.id,}, (res) => {
      if (res.errno == 0) {
        emit("update:tableTotal", props.tableTotal - res.data || 0);
        dataList.value.splice(index1, 1);
      }
      uni.hideLoading();

    });
    // 删除一级评论

  }
  delCloseFun();
}

// 展开评论if
function expandTxtShow({item1, index1}) {
  if (item1.comment_count > 0) {
    if (item1.children?.length) {
      return item1.children.length < item1.comment_count;
    } else {
      return true;
    }
  } else {
    return false
  }

}

// 展开更多评论
function expandReplyFun({item1, index1}) {
  // let csLen = dataList.value[index1].childrenShow.length;
  // dataList.value[index1].childrenShow.push(
  //     ...dataList.value[index1].children.slice(csLen, csLen + 6) // 截取5条评论
  // );
  getMoreReplyFun({item1, index1})
}

// 获取更多评论
function handleAddPage() {
  emit("handleAddPage", (res) => {
    // const newList = treeTransForm(res)
    dataList.value.push(...res)
  })

}

//获取更多评论
function getMoreReplyFun({item1, index1}) {

  uni.showLoading({
    title: "正在获取",
    mask: true,
  });
  let params = {
    id: item1.id,
    page: Math.ceil(item1.children || 0 / 20),
    size: 20,
  };
  if (item1.comment_count >= params.page * params.size) {
    params.page++
  }
  emit("getMoreReply", params, (res) => {
    uni.hideLoading();
    // 拿到后端返回的id赋值, 因为删除要用到id
    console.log(res)
    let c_data = dataList.value[index1];
    (c_data.children || (c_data.children = [])).push(...res);
  });
}

// 收起评论if
function shrinkTxtShow({item1, index1}) {
  return item1.childrenShow?.length >= 2 && item1.children.length - item1.childrenShow.length === 0;
}

// 收起更多评论
function shrinkReplyFun({item1, index1}) {
  dataList.value[index1].children = []
}
</script>

<style lang="scss" scoped>
$uni-bg-color-grey: grey;
$uni-text-color-disable: #999;
$uni-color-primary: #555555;
$uni-text-color-grey: grey;
.comment_box {
  width: 100%;
}

.center {
  display: flex;
  align-items: center;
}

.c_total {
  padding: 20rpx 30rpx 0 30rpx;
  font-size: 28rpx;
}

.empty_box {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  padding: 150rpx 10rpx;
  font-size: 28rpx;

  .txt {
    color: $uni-text-color-disable;
  }

  .click {
    color: $uni-color-primary;
  }
}

.c_comment {
  width: 100%;
  padding: 20rpx 0rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  border-bottom: 1px solid #eff2f3;

  .children_item {
    padding: 20rpx 0 0 0rpx;
    margin-top: 10rpx;
    margin-left: 70rpx;
    background-color: #fff;

    .expand_reply,
    .shrink_reply {
      margin-top: 10rpx;
      margin-left: 0rpx;

      .txt {
        font-weight: 600;
        color: $uni-color-primary;
      }
    }
  }
}

.c_popup_box {
  background-color: #fff;
  width: 750rpx;

  .reply_text {
    @extend .center;
    padding: 20rpx 20rpx 0 20rpx;
    font-size: 26rpx;

    .text_aid {
      color: $uni-text-color-grey;
      margin-right: 5rpx;
    }

    .user_avatar {
      width: 48rpx;
      height: 48rpx;
      border-radius: 50%;
      margin-right: 6rpx;
      margin-left: 12rpx;
    }

    .text_main {
    }
  }

  .content11 {
    width: 750rpx;
    display: flex;
    flex-direction: row;
    align-items: end;
    align-items: flex-end;

    .text_area {
      width: 588rpx;
      padding: 15rpx 10rpx 20rpx;
    }

    .send_btn {
      margin: 0 20rpx 20rpx 20rpx;
      width: 88rpx;
      height: 52rpx;
      background: #F67800;
      border-radius: 60rpx 60rpx 60rpx 60rpx;

      .text_w {
        color: #fff;
      }
    }
  }
}

.jzLoding {
  padding-bottom: 100rpx;

  .jzText {
    padding: 40rpx;
  }
}

//#ifdef APP-PLUS-NVUE
.nvueW {
  width: 710rpx;
}

//#endif
</style>
